import 'package:fish_redux/fish_redux.dart';
import '../OrderView/model/order_view_model.dart';
import 'action.dart';
import 'state.dart';

Reducer<PatrolOrderViewState> buildReducer() {
  return asReducer(
    <Object, Reducer<PatrolOrderViewState>>{
      PatrolOrderViewAction.action: _onAction,
      PatrolOrderViewAction.onGetData: _onGetData,
      PatrolOrderViewAction.onSetConfigData: _onSetConfigData,
      PatrolOrderViewAction.onSetNormalData: _onSetNormalData,
      PatrolOrderViewAction.onTapOther: _onTapOther,
    },
  );
}

PatrolOrderViewState _onAction(PatrolOrderViewState state, Action action) {
  final PatrolOrderViewState newState = state.clone();
  return newState;
}

PatrolOrderViewState _onGetData(PatrolOrderViewState state, Action action) {
  final PatrolOrderViewState newState = state.clone()..items = action.payload;
  return newState;
}

PatrolOrderViewState _onSetConfigData(
    PatrolOrderViewState state, Action action) {
  final PatrolOrderViewState newState = state.clone();
  OrderConfigModel model = action.payload['model'];
  ConfigValue data = action.payload['data'];
  if (model.values.contains(data)) {
    model.values.remove(data);
  } else {
    model.values.add(data);
  }
  model.isNormal = false;
  if (newState.items.indexOf(model) == newState.items.length - 1)
    model.isNormal = true;
  return newState;
}

PatrolOrderViewState _onSetNormalData(
    PatrolOrderViewState state, Action action) {
  final PatrolOrderViewState newState = state.clone();
  OrderConfigModel model = action.payload;
  model.isNormal = true;
  model.hasOther = false;
  model.values.clear();
  model.imageList.clear();
  model.textEditingController.clear();
  return newState;
}

PatrolOrderViewState _onTapOther(PatrolOrderViewState state, Action action) {
  final PatrolOrderViewState newState = state.clone();
  OrderConfigModel model = action.payload;
  model.hasOther = !model.hasOther;
  if (model.hasOther) model.isNormal = false;
  return newState;
}
